import re


def combine_short(file_path):
    with open(file_path, 'r', encoding='utf-8') as srt_file:
        lines = srt_file.readlines()

    new_lines = []  # 保存时间戳和字幕，后面可用它来重新生成 序号
    current_time = ""

    last_short = False
    last_time = ""
    last_line = ""
    for line in lines:
        line = line.strip()
        if line.isdigit():
            continue
        elif '-->' in line:
            current_time = line
        elif line != '':
            words = re.findall(r'\b\w+\b', line)  # Splitting line into words
            # 检查当前句是否是短句
            if len(words) <= 3:
                # 检查上一句是否是短句
                if last_short:
                    # 检查时间戳是否相近
                    if compare_time(last_time, current_time):
                        last_short = False
                        # 删除最后两个元素
                        new_lines = new_lines[:-2]
                        # 连接时间和字幕
                        new_time = last_time.split(' ')[0] + ' --> ' + current_time.split(' ')[2]
                        new_line = last_line + " " + line + "\n"
                        new_lines.append(new_time)
                        new_lines.append(new_line)
                    else:
                        new_lines.append(current_time)
                        new_lines.append(line + "\n")
                else:
                    last_short = True
                    last_line = line
                    last_time = current_time
                    new_lines.append(current_time)
                    new_lines.append(line + "\n")
            else:
                last_short = False
                new_lines.append(current_time)
                new_lines.append(line + "\n")

    new_lines_with_numbers = []
    # 遍历 new_lines 中的每一行
    num_index = 1
    for idx, line in enumerate(new_lines, start=1):  # start=1 使得 idx 从 1 开始
        if "-->" in line:
            # 插入序号化的字符串到 new_lines_with_numbers 中
            new_lines_with_numbers.append(f"{num_index}")
            new_lines_with_numbers.append(f"{line}")
            num_index += 1
        else:
            # 否则，直接添加原始字符串
            new_lines_with_numbers.append(line)

    # Writing to a new srt file
    with open(file_path, 'w', encoding='utf-8') as new_srt_file:
        new_srt_file.write('\n'.join(new_lines_with_numbers))


def compare_time(timestamp1, timestamp2):
    # 将时间戳转换为秒
    time1_seconds = timestamp_to_seconds(timestamp1.split(' ')[2])
    time2_seconds = timestamp_to_seconds(timestamp2.split(' ')[0])
    # 计算两个时间戳之间的差
    time_difference = abs(time1_seconds - time2_seconds)

    # 检查差是否小于等于1秒
    if time_difference <= 1:
        return True
    else:
        return False


def timestamp_to_seconds(timestamp):
    # 将时间戳转换为秒
    parts = timestamp.replace(',', '.').split(':')
    hours = int(parts[0])
    minutes = int(parts[1])
    seconds = float(parts[2])
    total_seconds = hours * 3600 + minutes * 60 + seconds
    return total_seconds